<template>
  <div
    class="m-dialog-wrapper"
    :class="className"
    v-if="visible"
    @click.self="handleWrapperClick"
  >
    <div class="m-dialog" :style="{ 'max-width': maxWidth }">
      <div class="m-dialog-header" v-if="showHeader">
        <slot name="dialog-header">
          <span class="title" :class="'is-' + headerAlign">{{ title }}</span>
          <span class="close" @click="handleDialogClose" v-if="showClose"
            >X</span
          >
          <div class="line"></div>
        </slot>
      </div>
      <div class="m-dialog-body">
        <div class="content">
          <slot></slot>
        </div>
      </div>
      <div class="m-dialog-footer" v-if="showFooter">
        <slot name="footer">
          <m-button @click="handleHide">取消</m-button>
          <m-button @click="handleSave" type="primary">保存</m-button>
        </slot>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
const props = defineProps({
  title: {
    // 标题名称
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  showHeader: {
    type: Boolean,
    default: true
  },
  width: {
    type: [Number, String],
    default: 550
  },
  className: {
    type: String,
    default: ''
  },
  headerAlign: {
    // 标题对齐方式
    type: String,
    default: 'left',
    validator(value) {
      // 这个值必须与下列字符串中的其中一个相匹配
      return ['left', 'right', 'center'].includes(value)
    }
  },
  closeOnClickModal: {
    // 是否可以通过点击 modal 关闭 Dialog
    type: Boolean,
    default: false
  },
  closeOnPressEscape: {
    // 是否可以通过按下 ESC 关闭 Dialog
    type: Boolean,
    default: false
  },
  showClose: {
    // 是否显示关闭按钮
    type: Boolean,
    default: true
  },
  beforeClose: Function,
  showFooter: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits(['update:visible', 'save'])

const maxWidth = computed(() => {
  return Number(props.width) ? props.width + 'px' : props.width
})

const handleWrapperClick = function () {
  if (!props.closeOnClickModal) return
  handleDialogClose()
}
const handleDialogClose = function () {
  if (typeof props.beforeClose === 'function') {
    props.beforeClose(handleHide)
  } else {
    handleHide()
  }
}
const handleHide = function (flag) {
  if (flag !== false) {
    emits('update:visible', false)
  }
}
const handleSave = function () {
  emits('save')
}
</script>
